
/*
 * GET users listing.
 */

var Lib = require('../lib/lib.js');
var User = require('../model/user.js');

exports.login = function(req,res){
    res.render('login', {
        title: '用户登录',
        user : req.session.user,
        success : req.flash('success').toString(),
        error : req.flash('error').toString()
    });
}


exports.doLogin = function(req,res){
    var password = Lib.MD5(req.body.password);

    User.getByName(req.body.username,function(err,result){
        if(err || !result){
            req.flash('error', '用户不存在');
            return res.redirect('/login');
        } else{
            if(result.password != password){
                req.flash('error', '密码错误');
                return res.redirect('/login');
            };
            req.session.user = result;
            req.flash('success', '登录成功');
            res.redirect('/');
        };
    });
}


exports.loginOut = function(req,res){
    req.session.user = null;
    req.flash('success', '注销成功');
    res.redirect('/');
}

exports.reg = function(req,res){
    res.render('reg',{
        title:'注册',
        user:req.session.user,
        success : req.flash('success').toString(),
        error : req.flash('error').toString()
    });
}

exports.doReg = function(req,res){

    if (req.body['password-repeat'] != req.body['password']) {
        req.flash('error', '两次输入的密码不一致');
        return res.redirect('/reg');
    }

    var password = Lib.MD5(req.body.password);

    User.insert(req.body.username,password,function(err,result){
        if(err || !result){
            req.session.user = null;
            req.flash('error','注册失败');
            res.redirect('/');
        }else{
            req.session.user = req.body.username;
            req.flash('success','注册成功');
            res.redirect('/');
        }
    })
}


exports.list = function(req, res){
  res.send("respond with a resource");
};


exports.userDetail = function(req,res){

}


exports.userProfile = function(req,res){

}

exports.doUserProfile = function(req,res){

}


exports.userList = function(req,res){

}